package com.ppc.service.impl;

import com.ppc.constant.EmployerConstant;
import com.ppc.constant.MessageConstant;
import com.ppc.constant.UserConstant;
import com.ppc.constant.WorkerConstant;
import com.ppc.dto.RegisterDTO;
import com.ppc.entity.Employer;
import com.ppc.entity.UserPPC;
import com.ppc.entity.Worker;
import com.ppc.exception.EmailException;
import com.ppc.exception.LoginFailedException;
import com.ppc.exception.RegisterFailedException;
import com.ppc.mapper.employer.EmployerMapper;
import com.ppc.mapper.user.UserMapper;
import com.ppc.mapper.worker.WorkerMapper;
import com.ppc.service.CommonService;
import com.ppc.utils.MailUtils;
import com.ppc.utils.MinIoUtil;
import com.ppc.utils.PhoneUtils;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

/**
 * @author jianKangS1
 * @date 2023/12/20
 */
@Service
public class CommonServiceImpl implements CommonService {

  @Autowired
  private UserMapper userMapper;

  @Autowired
  private EmployerMapper employerMapper;

  @Autowired
  private WorkerMapper workerMapper;

  @Autowired
  private MinIoUtil minIoUtil;

  @Autowired
  private PhoneUtils phoneUtils;

  /**
   * @param length
   * @return {@link String }
   * @description
   */
  private static String generateVerifyCode(int length) {
    // 生成length位数字验证码
    Random random = new Random();
    String verifyCode = "";
    for (int i = 0; i < length; i++) {
      Integer num = random.nextInt(10);
      verifyCode += num.toString();
    }
    return verifyCode;
  }


  /**
   * 验证邮箱
   *
   * @param email
   * @return {@link String }
   * @description
   */
  @Override
  public String verifyEmail(String email) {
    //邮箱不合法
    if (!MailUtils.checkMailVaild(email)) {
      throw new EmailException(MessageConstant.EMAIL_NOT_VAILD);
    }

    String verifyCode = generateVerifyCode(6);

    //发送消息失败
    boolean flag = MailUtils.sendQQMail(email, verifyCode);

    if (!flag) {
      throw new LoginFailedException(MessageConstant.SEND_EMAIL_FAILED);
    }

    return verifyCode;
  }

  /**
   * 验证手机
   *
   * @param phone
   * @return {@link String }
   * @description
   */
  @Override
  public String verifyPhone(String phone) {
    String verifyCode = generateVerifyCode(4);
    phoneUtils.sendMessage(phone, verifyCode);
    return verifyCode;
  }

  /**
   * 看email phone 有没有被注册
   *
   * @param phone
   * @param email
   * @return boolean
   * @description
   *///根据邮箱或者电话，查询用户是否存在
  @Override
  public boolean checkUserExist(String phone, String email) {
    if (email == null && phone == null) {
      throw new EmailException(MessageConstant.EMAIL_OR_PHONE_ERROR);
    }

    List<UserPPC> userList = userMapper.getUserByPhoneOrEmail(phone, email);
    return userList.size() > 0;
  }


  /**
   * 注册
   *
   * @param registerDTO
   * @return {@link Long }
   * @description
   */
  @Override
  @Transactional
  public Long register(RegisterDTO registerDTO) {
    if (!checkUserExist(registerDTO.getPhone(), registerDTO.getEmail())) {
      //用户不存在
      UserPPC userPPC = UserPPC.builder()
          .userName(UserConstant.NAME_DEFAULT)
          .userPhone(registerDTO.getPhone())
          .userEmail(registerDTO.getEmail())
          .userPassword(DigestUtils.md5DigestAsHex(registerDTO.getPassword().getBytes()))
          .fileId(UserConstant.FILE_DEFAULT)
          .build();

      userMapper.insertUserPPC(userPPC);

      if (registerDTO.getUserType() == UserConstant.EMPLOYER) {
        Employer employer = Employer.builder()
            .userId(userPPC.getUserId())
            .employerStatus(EmployerConstant.ENABLE)
            .employerCredit(EmployerConstant.CREDIT_DEFAULT)
            .employerCreateTime(LocalDateTime.now())
            .updateTime(LocalDateTime.now())
            .build();
        employerMapper.insertEmployer(employer);
        return employer.getUserId();
      } else if (registerDTO.getUserType() == UserConstant.WORKER) {
        Worker worker = Worker.builder()
            .userId(userPPC.getUserId())
            .workerStatus(WorkerConstant.ENABLE)
            .workerCredit(WorkerConstant.CREDIT_DEFAULT)
            .workerCount(WorkerConstant.COUNT_DEFAULT)
            .workerCreateTime(LocalDateTime.now())
            .updateTime(LocalDateTime.now())
            .build();

        workerMapper.insertWorker(worker);
        return worker.getUserId();
      } else {
        throw new RegisterFailedException(MessageConstant.UNKNOW_USERTYPE);
      }

    } else {
      throw new RegisterFailedException(MessageConstant.ACCOUNT_ALREADY_EXISTS);
    }
  }


}
